package com.company.utils;

import com.company.model.result.CaptchaImageResult;
import com.github.bingoohuang.patchca.color.ColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.DiffuseRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.DoubleRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.MarbleRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.WobbleRippleFilterFactory;
import com.github.bingoohuang.patchca.service.Captcha;
import com.github.bingoohuang.patchca.word.RandomWordFactory;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import javax.imageio.ImageIO;

/**
 * 图片验证码生成工具
 */
public class ImageCodeUtil {

  private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
  private static Random random = new Random();

  static {
    cs.setColorFactory(new ColorFactory() {
      @Override
      public Color getColor(int x) {
        int[] c = new int[3];
        int i = random.nextInt(c.length);
        for (int fi = 0; fi < c.length; fi++) {
          if (fi == i) {
            c[fi] = random.nextInt(71);
          } else {
            c[fi] = random.nextInt(256);
          }
        }
        return new Color(c[0], c[1], c[2]);
      }
    });
    RandomWordFactory wf = new RandomWordFactory();
    wf.setCharacters("23456789abcdefghgkmnpqrstuvwxyzABCDEFGHGKLMNPQRSTUVWXYZ");
    wf.setMaxLength(4);
    wf.setMinLength(4);
    cs.setWordFactory(wf);
  }


  public static CaptchaImageResult createImageCode() throws IOException {
    switch (random.nextInt(5)) {
      case 0:
        cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
        break;
      case 1:
        cs.setFilterFactory(new MarbleRippleFilterFactory());
        break;
      case 2:
        cs.setFilterFactory(new DoubleRippleFilterFactory());
        break;
      case 3:
        cs.setFilterFactory(new WobbleRippleFilterFactory());
        break;
      case 4:
        cs.setFilterFactory(new DiffuseRippleFilterFactory());
        break;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Captcha captcha = cs.getCaptcha();
    ImageIO.write(captcha.getImage(), "png", out);

    byte[] bytes = out.toByteArray();
    String uuid = UUID.randomUUID().toString();
    CaptchaImageResult imageCodeResultVO = new CaptchaImageResult(uuid, bytes,
        captcha.getChallenge());
    return imageCodeResultVO;
  }
}
